import React, { useContext, useState, useEffect, useRef } from 'react';
import { Context } from '@/store/Context';
import { CustomImage } from '@/draw/CustomImage';
import Range from '@/components/range';
import styles from './index.module.less';
import { Button, Upload } from 'antd';
import { UploadChangeParam, UploadFile } from 'antd/es/upload';

// 像素转毫米的转换比例（96 DPI: 1mm ≈ 3.779527559px）
const PX_TO_MM = 3.779527559;
const MM_TO_PX = 1 / PX_TO_MM;

const Edit = () => {
    const { canvas, setState, currentTab } = useContext(Context);
    const [localObject, setLocalObject] = useState<CustomImage | null>(null);
    const [positionX, setPositionX] = useState(0);
    const [positionY, setPositionY] = useState(0);
    const [scale, setScale] = useState(100);
    const [rotation, setRotation] = useState(0);
    const fileInputRef = useRef<HTMLInputElement>(null);

    // 监听对象变化，同步更新UI
    useEffect(() => {
        if (!localObject || !canvas) return;

        const updateValues = () => {
            const left = localObject.left || 0;
            const top = localObject.top || 0;
            const scaleX = (localObject.scaleX || 1) * 100;
            const angle = localObject.angle || 0;
            
            setPositionX(Math.round(left * MM_TO_PX * 100) / 100);
            setPositionY(Math.round(top * MM_TO_PX * 100) / 100);
            setScale(Math.round(scaleX));
            setRotation(Math.round(angle));
        };

        canvas.on('object:modified', updateValues);
        canvas.on('object:moving', updateValues);
        canvas.on('object:scaling', updateValues);
        canvas.on('object:rotating', updateValues);

        return () => {
            canvas.off('object:modified', updateValues);
            canvas.off('object:moving', updateValues);
            canvas.off('object:scaling', updateValues);
            canvas.off('object:rotating', updateValues);
        };
    }, [localObject, canvas]);

    // 替换图片
    const handleReplaceImage = () => {
        if (fileInputRef.current) {
            fileInputRef.current.click();
        }
    };

    const handleFileChange = (info: UploadChangeParam<UploadFile<any>>) => {
        const file = info.file.originFileObj as File;
        if (!file || !canvas) return;

        if (!file.type.startsWith('image/')) {
            alert('请选择图片文件');
            return;
        }

        const reader = new FileReader();
        reader.onload = (evt) => {
          if (!evt.target || !canvas) return;

          const imgSrc = evt.target.result as string;
          const img = new Image();
          img.crossOrigin = 'anonymous';
          img.src = imgSrc;
            
          img.onload = () => {
              // 保存当前的位置、缩放和旋转等属性
            if (!localObject) {
              const newImage = new CustomImage(img, {
                  maskType: 'none',
                  brightness: 0,
                  contrast: 0,
                  saturation: 0,
              });

              newImage.set({
                selectable: true,
                evented: true
            });

            canvas.add(newImage);
            canvas.setActiveObject(newImage);
            canvas.renderAll();
            setLocalObject(newImage);
            setState({ currentImage: newImage });
            if (currentTab === 'front') {
                setState({ frontImage: newImage });
            } else {
                setState({ backImage: newImage });
            }
            return;
          }
								
          const currentLeft = localObject.left || 0;
          const currentTop = localObject.top || 0;
          const currentScaleX = localObject.scaleX || 1;
          const currentScaleY = localObject.scaleY || 1;
          const currentAngle = localObject.angle || 0;
          const currentMaskType = localObject.maskType || 'none';
          const currentBrightness = localObject.brightness || 0;
          const currentContrast = localObject.contrast || 0;
          const currentSaturation = localObject.saturation || 0;

          // 创建新的CustomImage实例
          const newImage = new CustomImage(img, {
              maskType: currentMaskType,
              brightness: currentBrightness,
              contrast: currentContrast,
              saturation: currentSaturation,
              left: currentLeft,
              top: currentTop,
              scaleX: currentScaleX,
              scaleY: currentScaleY,
              angle: currentAngle,
              selectable: true,
              evented: true,
          });

          // 获取旧图片在画布中的索引
          const objects = canvas.getObjects();
          const oldIndex = objects.indexOf(localObject);

          // 移除旧图片，添加新图片
          canvas.remove(localObject);
          canvas.insertAt(newImage, oldIndex, false);
          canvas.setActiveObject(newImage);
          canvas.renderAll();

          // 更新选中的对象
          setState({ currentImage: newImage });
          setLocalObject(newImage);
        };
      };
        
      reader.readAsDataURL(file);
    };

    // 删除图片
    const handleDeleteImage = () => {
        if (!localObject || !canvas) return;
        
        canvas.remove(localObject);
        canvas.discardActiveObject();
        canvas.renderAll();
        setState({ currentImage: null });
    };

    // 位置改变
    const handlePositionChange = (axis: 'x' | 'y', value: string) => {
        if (!localObject || !canvas) return;
        
        const mmValue = parseFloat(value) || 0;
        const pxValue = mmValue * PX_TO_MM;
        
        if (axis === 'x') {
            setPositionX(mmValue);
            localObject.set({ left: pxValue });
        } else {
            setPositionY(mmValue);
            localObject.set({ top: pxValue });
        }
        
        canvas.renderAll();
    };

    // 缩放改变
    const handleScaleChange = (value: number) => {
        if (!localObject || !canvas) return;
        
        setScale(value);
        const scaleValue = value / 100;
        localObject.set({
            scaleX: scaleValue,
            scaleY: scaleValue,
        });
        canvas.renderAll();
    };

    // 旋转改变
    const handleRotationChange = (value: number) => {
        if (!localObject || !canvas) return;
        
        setRotation(value);
        localObject.set({ angle: value });
        canvas.renderAll();
    };

    // 水平居中
    const handleCenterHorizontal = () => {
        if (!localObject || !canvas) return;
        
        const canvasWidth = canvas.getWidth();
        const objectWidth = (localObject.width || 0) * (localObject.scaleX || 1);
        const left = (canvasWidth - objectWidth) / 2;
        
        localObject.set({ left });
        setPositionX(Math.round(left * MM_TO_PX * 100) / 100);
        canvas.renderAll();
    };

    // 垂直居中
    const handleCenterVertical = () => {
        if (!localObject || !canvas) return;
        
        const canvasHeight = canvas.getHeight();
        const objectHeight = (localObject.height || 0) * (localObject.scaleY || 1);
        const top = (canvasHeight - objectHeight) / 2;
        
        localObject.set({ top });
        setPositionY(Math.round(top * MM_TO_PX * 100) / 100);
        canvas.renderAll();
    };

    // 上下翻转
    const handleFlipVertical = () => {
        if (!localObject || !canvas) return;
        
        const currentScaleY = localObject.scaleY || 1;
        localObject.set({ scaleY: -currentScaleY });
        canvas.renderAll();
    };

    // 左右翻转
    const handleFlipHorizontal = () => {
        if (!localObject || !canvas) return;
        
        const currentScaleX = localObject.scaleX || 1;
        localObject.set({ scaleX: -currentScaleX });
        canvas.renderAll();
    };

    // 逆时针旋转90度
    const handleRotateLeft = () => {
        if (!localObject || !canvas) return;
        
        const currentAngle = localObject.angle || 0;
        const newAngle = currentAngle - 90;
        localObject.set({ angle: newAngle });
        setRotation(newAngle);
        canvas.renderAll();
    };

    // 顺时针旋转90度
    const handleRotateRight = () => {
        if (!localObject || !canvas) return;
        
        const currentAngle = localObject.angle || 0;
        const newAngle = currentAngle + 90;
        localObject.set({ angle: newAngle });
        setRotation(newAngle);
        canvas.renderAll();
    };

    // if (!localObject) {
    //     return (
    //         <div className={styles.wrap}>
    //             <div>请选择一个图片对象</div>
    //         </div>
    //     );
    // }

    return (
        <div className={styles.wrap}>
            {/* 替换和删除按钮 */}
            <div className={styles.button_group}>
                <Upload showUploadList={false} accept="image/*" onChange={handleFileChange} customRequest={() => {}}>
                    <Button>替换图片</Button>
                </Upload>
                <Button onClick={handleDeleteImage}>删除图片</Button>
                {/* <button onClick={} className={styles.btn}>
                    删除图片
                </button> */}
            </div>

            {/* 图片位置 */}
            {/* <div className={styles.props_section}>
                <div className={styles.props_group_label}>图片位置</div>
                <div className={styles.position_inputs}>
                    <div className={styles.input_group}>
                        <label>X</label>
                        <input
                            type="number"
                            value={positionX}
                            onChange={(e) => handlePositionChange('x', e.target.value)}
                            className={styles.position_input}
                        />
                        <span className={styles.unit}>mm</span>
                    </div>
                    <div className={styles.input_group}>
                        <label>Y</label>
                        <input
                            type="number"
                            value={positionY}
                            onChange={(e) => handlePositionChange('y', e.target.value)}
                            className={styles.position_input}
                        />
                        <span className={styles.unit}>mm</span>
                    </div>
                </div>
            </div> */}

            {/* 图片操作 */}
            <div className={styles.props_section}>
                <div className={styles.props_group_label}>图片操作</div>
                <div className={styles.operation_buttons}>
                    <button
                        onClick={handleCenterHorizontal}
                        className={styles.operation_btn}
                        title="水平居中"
                    >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                            <path d="M2 8h12M8 2v12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                            <path d="M4 6h8M4 10h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                        </svg>
                    </button>
                    <button
                        onClick={handleCenterVertical}
                        className={styles.operation_btn}
                        title="垂直居中"
                    >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                            <path d="M8 2v12M2 8h12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                            <path d="M6 4v8M10 4v8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                        </svg>
                    </button>
                    <button
                        onClick={handleFlipVertical}
                        className={styles.operation_btn}
                        title="上下翻转"
                    >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                            <path d="M8 2v12M4 6l4-4 4 4M4 10l4 4 4-4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                    </button>
                    <button
                        onClick={handleFlipHorizontal}
                        className={styles.operation_btn}
                        title="左右翻转"
                    >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                            <path d="M2 8h12M6 4l-4 4 4 4M10 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                    </button>
                    <button
                        onClick={handleRotateLeft}
                        className={styles.operation_btn}
                        title="逆时针旋转90°"
                    >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                            <path d="M8 4v8M4 8h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                            <path d="M6 6l-2-2 2-2M10 6l2-2-2-2" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                    </button>
                    <button
                        onClick={handleRotateRight}
                        className={styles.operation_btn}
                        title="顺时针旋转90°"
                    >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                            <path d="M8 4v8M4 8h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                            <path d="M10 10l2 2-2 2M6 10l-2 2 2 2" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                    </button>
                </div>
            </div>

            {/* 图片缩放 */}
            <div className={styles.props_section}>
                <div className={styles.props_group_label}>图片缩放</div>
                <Range
                    min={1}
                    max={500}
                    value={scale}
                    onChange={handleScaleChange}
                    unit="%"
                />
            </div>

            {/* 图片旋转 */}
            <div className={styles.props_section}>
                <div className={styles.props_group_label}>图片旋转</div>
                <Range
                    min={-180}
                    max={180}
                    value={rotation}
                    onChange={handleRotationChange}
                    unit="°"
                />
            </div>
        </div>
    );
};

export default Edit;